﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;

namespace Universe.SimpleQueue.Tests
{
    public static class MutexExtentions
    {

        // Deisgned for using(...) usage only
        public static IDisposable CrossProcessLock(this string globalResourceId)
        {
            if (globalResourceId == null) 
                throw new ArgumentNullException("globalResourceId");

            if (string.IsNullOrWhiteSpace(globalResourceId))
                throw new ArgumentException("Empty string isnt valid", "globalResourceId");

            Mutex m = new Mutex(false, SafePath(globalResourceId).Replace("\\", "_"));
            m.WaitOne();

            return new Disposable() {M = m};
        }

        static string SafePath(string path)
        {
            StringBuilder ret = new StringBuilder();
            var ic = Path.GetInvalidPathChars(); 
            foreach (var c in path)
                ret.Append(ic.Contains(c) ? '_' : c);

            return ret.ToString();
        }


        class Disposable : IDisposable
        {
            public Mutex M;

            // By Design this code is always single threaded
            public void Dispose()
            {
                if (M != null)
                    M.ReleaseMutex();

                M = null;
            }
        }

    }
}
